const baseURL: string = import.meta.env.VITE_API_URL;
// 添加拦截器
const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        // 1.非http
        if (!options.url.startsWith('http')) {
            options.url = baseURL + options.url
        }
        // 2.超时
        options.timeout = 10000
        // 3.添加请求头
        options.header = {
            ...options.header,
        }
        // 4.添加token请求头标识
		const useStore = UseStore();
        const token = useStore?.getUserToken
        if (token) {
            options.header.access_token = token
        }
    }
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

interface Data<T> {
[x: string]: object;
	code: string|number,
    msg: string,
    result: T,
}

export const request = <T>(options: UniApp.RequestOptions)=>{
	return new Promise<Data<T>>((resolve,reject)=>{
		uni.request({
			...options,
			success(res:any){
				switch(res.data.code){
					case 200:
						case '200':
						resolve(res.data as Data<T>);
					break;
					case 401:
						case '401':
						uni.reLaunch({
							url:'/pages/login/login'
						})
						reject(res.data)
					break;
					case 500:
						case '500':
						uni.showToast({
							title:res.msg,
							icon:'none'
						})
						reject(res.data)
					break;
					default:
						
						reject(res.data)
					break;
				}
			},
			fail(error){
				uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                })
                reject(error)

			}
		})
	})
}
